package main

import (
	"django_blog_gin/internal/config"
	"flag"
	"fmt"
	"strings"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
	_ "github.com/lib/pq"
)

// func main() {
// 	config.ReadFileSettings("settings.yaml")
// 	MysqlToPgMigrate()
// }

func MysqlToPgMigrate() {
	pgDsn := config.GlobalConfig.Pg.GenerateDns()
	mysqlDsn := config.GlobalConfig.Mysql.GenerateDns()

	tables := flag.String("tables", "", "要迁移的表名,逗号分隔")
	flag.Parse()

	if *tables == "" {
		fmt.Println("请指定要迁移的表名, 例如: --tables=accounts_bloguser,blog_tag")
		return
	}

	mysqlDb, err := sqlx.Open("mysql", mysqlDsn)
	if err != nil {
		panic(err)
	}
	defer mysqlDb.Close()

	pgDb, err := sqlx.Open("postgres", pgDsn)
	if err != nil {
		panic(err)
	}
	defer pgDb.Close()

	tableList := strings.Split(*tables, ",")
	for _, table := range tableList {
		table = strings.TrimSpace(table)
		fmt.Printf("迁移表: %s\n", table)
		migrateTable(mysqlDb, pgDb, table)
	}
}

func migrateTable(mysqlDb, pgDb *sqlx.DB, table string) {
	rows, err := mysqlDb.Queryx(fmt.Sprintf("SELECT * FROM %s", table))
	if err != nil {
		fmt.Printf("读取MySQL表失败: %s\n", err)
		return
	}
	defer rows.Close()

	cols, _ := rows.Columns()
	for rows.Next() {
		data := make(map[string]interface{})
		if err := rows.MapScan(data); err != nil {
			fmt.Printf("行数据解析失败: %s\n", err)
			continue
		}
		// 构造PG插入SQL
		fields := []string{}
		placeholders := []string{}
		values := []interface{}{}
		idx := 1
		for _, col := range cols {
			fields = append(fields, col)
			placeholders = append(placeholders, fmt.Sprintf("$%d", idx))
			values = append(values, data[col])
			idx++
		}
		insertSql := fmt.Sprintf("INSERT INTO %s (%s) VALUES (%s)", table, strings.Join(fields, ","), strings.Join(placeholders, ","))
		_, err := pgDb.Exec(insertSql, values...)
		if err != nil {
			fmt.Printf("PG插入失败: %s\n", err)
		}
	}
}
